package com.styletransfer.service;

import com.styletransfer.exception.BusinessException;
import com.styletransfer.mapper.CombinationMapper;
import com.styletransfer.mapper.LikeMapper;
import com.styletransfer.mapper.StyleMapper;
import com.styletransfer.mapper.WorkMapper;
import com.styletransfer.mapper.AlbumMapper;
import com.styletransfer.model.ApiResponse;
import com.styletransfer.model.Like;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 点赞服务类
 *
 * 这个类负责处理与点赞相关的业务逻辑，包括用户对风格、组合和作品的点赞操作。
 */
@Service
public class LikeService {

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private StyleMapper styleMapper;

    @Autowired
    private CombinationMapper combinationMapper;

    @Autowired
    private WorkMapper workMapper;
    
    @Autowired
    private AlbumMapper albumMapper;

    /**
     * 添加点赞
     *
     * @param like 点赞对象
     * @return API响应
     */
    @Transactional
    public ApiResponse<Like> addLike(Like like) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();
        like.setUserId(userId);

        // 检查点赞类型
        if (like.getType() == null) {
            throw new BusinessException("点赞类型不能为空");
        }

        // 检查点赞对象是否存在
        if (like.getType() == 1) { // 风格
            if (styleMapper.findById(like.getTargetId()) == null) {
                throw new BusinessException("风格不存在");
            }
        } else if (like.getType() == 2) { // 组合
            if (combinationMapper.findById(like.getTargetId()) == null) {
                throw new BusinessException("组合不存在");
            }
        } else if (like.getType() == 3) { // 作品
            if (workMapper.findById(like.getTargetId()) == null) {
                throw new BusinessException("作品不存在");
            }
        } else if (like.getType() == 4) { // 专辑
            if (albumMapper.findById(like.getTargetId()) == null) {
                throw new BusinessException("专辑不存在");
            }
        } else {
            throw new BusinessException("点赞类型无效");
        }

        // 检查是否已点赞
        Like existingLike = likeMapper.findByUserAndTarget(userId, like.getTargetId(),like.getType());
        if (existingLike != null) {
            throw new BusinessException("已经点赞过了");
        }

        // 设置默认值
        like.setCreateTime(new Date());

        // 插入点赞
        likeMapper.insert(like);

        // 增加点赞数
        if (like.getType() == 1) { // 风格
            styleMapper.incrementLikeCount(like.getTargetId());
        } else if (like.getType() == 2) { // 组合
            combinationMapper.incrementLikeCount(like.getTargetId());
        } else if (like.getType() == 3) { // 作品
            workMapper.incrementLikeCount(like.getTargetId());
        } else if (like.getType() == 4) { // 专辑
            albumMapper.incrementLikeCount(like.getTargetId());
        }

        return ApiResponse.success(like);
    }

    /**
     * 取消点赞
     *
     * @param type 点赞类型（1:风格, 2:组合, 3:作品, 4:专辑）
     * @param targetId 目标ID
     * @return API响应
     */
    @Transactional
    public ApiResponse<Void> cancelLike(Integer type, Long targetId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 检查是否已点赞
        Like like = likeMapper.findByUserAndTarget(userId, targetId, type);
        if (like == null) {
            throw new BusinessException("未点赞过");
        }

        // 删除点赞
        likeMapper.delete(like.getId());

        // 减少点赞数
        if (type == 1) { // 风格
            styleMapper.decrementLikeCount(targetId);
        } else if (type == 2) { // 组合
            combinationMapper.decrementLikeCount(targetId);
        } else if (type == 3) { // 作品
            workMapper.decrementLikeCount(targetId);
        } else if (type == 4) { // 专辑
            albumMapper.decrementLikeCount(targetId);
        }

        return ApiResponse.success();
    }

    /**
     * 检查是否已点赞
     *
     * @param type 点赞类型（1:风格, 2:组合, 3:作品, 4:专辑）
     * @param targetId 目标ID
     * @return API响应
     */
    public ApiResponse<Boolean> checkLike(Integer type, Long targetId) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 检查是否已点赞
        Like like = likeMapper.findByUserAndTarget(userId, targetId, type);

        return ApiResponse.success(like != null);
    }

    /**
     * 查询用户的点赞
     *
     * @param type 点赞类型（1:风格, 2:组合, 3:作品, 4:专辑）
     * @return API响应
     */
    public ApiResponse<List<Like>> findByUser(Integer type) {
        // 获取当前登录用户ID
        Long userId = getCurrentUserId();

        // 查询点赞
        List<Like> likes = likeMapper.findByUser(userId, type);

        return ApiResponse.success(likes);
    }

    /**
     * 查询目标的点赞数
     *
     * @param type 点赞类型（1:风格, 2:组合, 3:作品, 4:专辑）
     * @param targetId 目标ID
     * @return API响应
     */
    public ApiResponse<Integer> countByTarget(Integer type, Long targetId) {
        // 查询点赞数
        Integer count = likeMapper.countByTarget(targetId,type);

        return ApiResponse.success(count);
    }

    /**
     * 获取用户收到的点赞总数
     *
     * @param userId 用户ID，如果不提供则获取当前登录用户的点赞数
     * @return API响应
     */
    public ApiResponse<Integer> countReceivedLikes(Long userId) {
        // 如果没有提供用户ID，则获取当前登录用户ID
        if (userId == null) {
            userId = getCurrentUserId();
        }
        
        // 查询用户作品获得的点赞数
        int likesCount = 0;
        
        try {
            // 获取用户的所有作品
            List<Long> workIds = workMapper.findWorkIdsByUserId(userId);
            
            // 统计所有作品的点赞数
            for (Long workId : workIds) {
                Integer count = likeMapper.countByTarget(workId, 3); // 3表示作品类型
                if (count != null) {
                    likesCount += count;
                }
            }
            
            // 获取用户的所有专辑
            List<Long> albumIds = albumMapper.findAlbumIdsByUserId(userId);
            
            // 统计所有专辑的点赞数
            for (Long albumId : albumIds) {
                Integer count = likeMapper.countByTarget(albumId, 4); // 4表示专辑类型
                if (count != null) {
                    likesCount += count;
                }
            }
            
            return ApiResponse.success(likesCount);
        } catch (Exception e) {
            return ApiResponse.error("获取用户点赞数失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Object principal = authentication.getPrincipal();

            // 从自定义UserDetails中获取用户ID
            if (principal instanceof com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) {
                return ((com.styletransfer.security.CustomUserDetailsService.CustomUserDetails) principal).getUserId();
            }

            // 尝试从请求属性中获取用户ID
            javax.servlet.http.HttpServletRequest request =
                    ((org.springframework.web.context.request.ServletRequestAttributes)
                            org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
            Object userId = request.getAttribute("userId");
            if (userId != null) {
                return (Long) userId;
            }

            throw new RuntimeException("无法获取用户ID");
        } catch (Exception e) {
            throw new RuntimeException("获取用户ID失败: " + e.getMessage());
        }
    }
}
